package org.study.itcast;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import static org.study.ByteBufferUtil.debugAll;

/**
 * @author: jzhou
 * @date: 2024/4/18-23:16
 * @version: 1.0
 * @description:
 */
@Slf4j
public class ChannelBufferDemo1 {
    public static void main(String[] args) {

        try (FileChannel channel = new FileInputStream("netty-demo/data.txt").getChannel()) {
            System.out.println(channel.size());
            //准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                // 从channel读 向buffer写入
                int len = channel.read(buffer);
                log.debug("读到字节数：{}", len);
                debugAll(buffer);
                if (len == -1) {
                    break; // 已到达文件末尾，退出循环
                }


                buffer.flip(); // 切换到读模式
                debugAll(buffer);
                while (buffer.hasRemaining()) { // 检查是否还有未读数据
                    byte b = buffer.get();
                    log.info("{}", (char) b); // 字节强转为字符
                }
                debugAll(buffer);

                // 切换 buffer 写模式
                buffer.clear();
            }
        } catch (IOException e) {
            log.error("An error occurred while reading the file:", e);
        }

    }
}
